import numpy as np
import h5py

def save_profile_data(h5_path, traces, midvalue,description=None):
    profile_file = h5py.File(h5_path, 'w')
    profile_file.create_dataset("traces", data=traces, compression='gzip', compression_opts=7)
    profile_file.create_dataset("midvalue", data=midvalue)
    profile_file.create_dataset("description", data=[str(description)])
    profile_file.flush()
    profile_file.close()

def save_analysis_data(h5_path, traces, midvalue, mkey=None,rkey=None, plaintext=None, ciphertext=None,description=None):
    analysis_file = h5py.File(h5_path, 'w')
    analysis_file.create_dataset(name="traces", data=traces, compression='gzip', compression_opts=7)
    analysis_file.create_dataset(name="midvalue", data=midvalue)
    analysis_file.create_dataset(name="description", data=[str(description)])
    metadata_group = analysis_file.create_group("metadata")
    if mkey is not None:
        metadata_group.create_dataset(name="mkey", data=mkey)
    if rkey is not None:
        metadata_group.create_dataset(name="rkey", data=rkey)
    if plaintext is not None:
        metadata_group.create_dataset(name="plaintext", data=plaintext)
    if ciphertext is not None:
        metadata_group.create_dataset(name="ciphertext", data=ciphertext)
    analysis_file.flush()
    analysis_file.close()

def get_profile_data(h5_path):
    profile_file = h5py.File(h5_path, "r")
    traces = np.array(profile_file['traces'])
    midvalue = np.array(profile_file['midvalue'],np.uint32)
    description = profile_file['description'][0].decode('utf-8')
    return traces, midvalue,description

def get_analysis_data(h5_path):
    analysis_file = h5py.File(h5_path, "r")
    traces = np.array(analysis_file['traces'])
    new_type = eval("np." + str(traces.dtype).replace('8', '32'))
    traces = np.array(traces, new_type)
    midvalue = np.array(analysis_file['midvalue'],np.uint32)
    description = analysis_file['description'][0].decode('utf-8')
    metadata = {}
    metadata_group = analysis_file['metadata']
    for key in metadata_group.keys():
        metadata[key] = np.array(metadata_group[key],np.uint32)
    return traces, midvalue, metadata,description